/*
 * Author: Alvin
 * Modified By: Alvin
 * Created Date: 2023-10-08 15:28:03
 * Last Modified: 2023-10-08 19:03:23
 * Description:
 */

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/api_exception.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/site/site_device_list/site_device_list_state.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

import '../../../components/log_utils.dart';
import '../../../routers/router_path.dart';

class SiteDeviceListController extends GetxController {
  final DeviceServices services = Get.put(DeviceServices());
  final SiteDeviceListState state = SiteDeviceListState();
  int siteId = 1;
  bool isShowPop = false;
  bool cameraIsDenied = true;
  bool isSort = false; //是否点击排序
  ScrollController scrollController = ScrollController();
  bool sortPermission = true;///排序权限
  bool addPermission = true;///添加权限
  bool unbindingPermission = true;///解绑权限
  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['siteId'];
      loadData(isloading: true);
    }
    sortPermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingDeviceSort]);
    addPermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingDeviceAdd]);
    unbindingPermission = FuncUtils.isPassAuthority([PermissionConstant.homeSiteManageSettingDeviceUnbind]);
    super.onInit();
  }

  @override
  void onReady() {

  }

  @override
  void onClose() {}

  Future refreshData({isLoading = false}) async {
    Log.d('refreshData===');
    state.pageNum = 1;
    await loadData(isloading: isLoading);
  }

  Future loadMoreData() async {
    // state.pageNum++;
    // await loadData(isloading: false);
  }

  loadData({isloading = false}) async {
    try {
      var params = {
        'current': state.pageNum,
        'pageSize': state.pageSize,
        'siteId': siteId,
        'productTypeId': '',
        'connectStatus': '',
        'name': '',
        'sn': '',
      };
      if (isloading) {
        showLoading(toast: ResKey.loading.tr);
      }
      if (state.pageNum == 1) state.dataList.clear();
      var response = await services.getDevicelist(params);
      state.refreshController.refreshCompleted();
      state.refreshController.loadComplete();
      var list = response['list'] ?? [];
      list.forEach(
          (item) => state.dataList.add(DeviceListModel.fromJson(item)));
      update();

      dismissLoading();
    } catch (e) {
      dismissLoading();
      handleException(ApiException.from(e));
      if (state.pageNum == 1) {
        state.refreshController.refreshFailed();
      } else {
        state.refreshController.loadFailed();
      }
    }
  }

  Future<void> requestCameraPermission() async {
    final status = await Permission.camera.request();
    Log.d('status===' + status.toString());
    if (status == PermissionStatus.denied ||
        status == PermissionStatus.permanentlyDenied) {
      // 摄像头权限被拒绝
      cameraIsDenied = true;
    } else {
      // 摄像头权限被拒绝
      cameraIsDenied = false;
    }
  }

  ///绑定新的设备
  void addNewDevice() {
    // Get.toNamed(RouterPath.siteDeviceAccess,arguments: {'siteId':siteId});
    isShowPop = !isShowPop;
    update();
  }

  ///排序
  void sortDevice() {
    isSort = !isSort;
    update();
  }

  ///排序完成
  void sortDeviceCompete() {
    isSort = false;
    update();
    updateSortDevice();
  }

  ///把排序传给后台
  void updateSortDevice() {
    List <dynamic> updateList = [];
    for (int i = 0; i < state.dataList.length; i++) {
      updateList. add({
        'deviceId':state.dataList[i].deviceId,
        'sort':i
      });
    }
    showLoading(toast: ResKey.loading.tr);
   var result =  services.updateDeviceModifySort(updateList,onError: (error){
     dismissLoading();
     showError(error.message.toString());
      return false;
    });
    dismissLoading();
    Log.d('updateList===' + updateList.toString());
    Log.d('updateList===' + result.toString());
  }

  ///录入按钮被点击
  void manualEntryOrScanEntry(
    int index,
  ) {
    //0为手动录入,1为扫码录入
    Log.d('manualEntryOrScanEntry==' + index.toString());
    isShowPop = false;
    update();
    if (index == 0) {
      // Get.toNamed(RouterPath.siteDeviceAccess);
      Get.toNamed(RouterPath.scanFailMannualAccess, arguments: {
        'siteId': siteId,
      });
    } else if (index == 1) {
      // if(cameraIsOpen){
      Get.toNamed(RouterPath.deviceScanner,
          arguments: {'siteId': siteId, 'cameraIsDenied': cameraIsDenied});
      // }else{
      //   EasyLoading.showError('请先打开相机权限再扫码');
      //   Future.delayed(const Duration(seconds: 2)).then((value)
      //   =>openAppSettings());
      // }
    }
  }

  ///解绑设备按钮被点击,1、安装商有解绑按钮（业主没有），所有在线设备均不能解绑；弹窗：当前设备处于在线状态，无法进行解绑操作
  /// 2、独立设备才可以解绑，由ocal EMS 和储能EMS上传上来的设备无解绑按钮（工商储机柜可以解绑）
  void tapDeviceHandler(DeviceListModel device, BuildContext? context) {
    Log.d('tapDeviceHandler==');
    // if (device.connectStatus == ConnectStatusType.off) {
    ///20240325 刘海确认在线也可以解绑的,不做限制
    //通信状态 0离线1在线 2未配置
    BrnDialogManager.showConfirmDialog(
      context!,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.confirm.tr,
      title: ResKey.siteAccessDeviceUnbindingDevice.tr,
      onCancel: () => Get.back(),
      onConfirm: () {
        Log.d('发送网络请求关闭页面');

        _unbindingDevice({'deviceId': device.deviceId});
        Get.back();
      },
    );
    // } else if (device.connectStatus == ConnectStatusType.on) {
    //   BrnDialogManager.showConfirmDialog(
    //     context!,
    //     cancel: ResKey.cancel.tr,
    //     confirm: ResKey.confirm.tr,
    //     title: '当前设备处于在线状态，无法进行解绑操作',
    //     onCancel: () => Get.back(),
    //     onConfirm: () {
    //       Get.back();
    //     },
    //   );
    // }
  }

  _unbindingDevice(param) async {
    Log.d('param==' + param.toString());
    showLoading(toast: ResKey.loading.tr);
    var response = await services.unbindingDevice(param, onError: (error) {
      dismissLoading();
      handleException(error);
      return false;
    });
    dismissLoading();
    Log.d('response==' + response.toString());
    if (response == true) {
      state.pageNum = 1;
      loadData(isloading: true);
    }
  }
}
